// pages/new-pages/my-employee/my-employee.js
const app = getApp();
import Toast from '../../../component/toast/toast';
import { formatAmount } from '../../../utils/util.js';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        positionId:1,
        hasMore:true,
        pageSize: 10,
        pageIndex: -1,
        employeeList:[]
    },
    //获取我的雇员列表
    getMyEmployee(data){
        console.log("getMyEmployee"+JSON.stringify(data));
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.getMyEmployee,
            data: data,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                console.log("getMyEmployee response" , res);
                if(res.statusCode == 200){
                    if (res.data.CodeStatus == 20000){
                        let count = res.data.BodyContent.TotalCount;
                        let flag = (that.data.pageIndex + 1) * that.data.pageSize < count;
                        let newList = that.data.employeeList.concat(res.data.BodyContent.List);
                        newList.forEach(function (item, index) {
                            newList[index]._amount = formatAmount(item.TotalFee);
                        });
                        that.setEmployeeOrderStatus(newList);
                        that.setData({
                            hasMore:flag,
                            employeeList:newList
                        })
                    }else{
                        that.setData({
                            hasMore:false
                        });
                    }
                }else{
                    Toast("请求失败了，请检查网络连接！");
                }
            },
            fail: function (res) { console.log("getMyEmployee fail" , res)},
            complete: function(res) {wx.hideLoading()},
        })
    },
    //根据订单状态设置页面的数据
    setEmployeeOrderStatus(list){
        let that = this;
        for(let i = 0; i < list.length; i++){
            let orderStatus = list[i].OrderStatus;
            switch (orderStatus) {
                case 0:
                    //甲方未付款
                    list[i].statusIcon = '../../../assets/icon/icon_is_confirm.png';
                    list[i].statusTxt = '待支付';
                    list[i].statusBtn = '去支付';
                    break;
                case 1:
                    //甲方已付款
                    list[i].statusIcon = '../../../assets/icon/icon_excuting.png';
                    list[i].statusTxt = '执行中';
                    if (this.data.positionId == 1){
                        list[i].statusBtn = '解雇';
                    }else{
                        list[i].statusBtn = '确认完成';
                    }
      
                    break;
                case 2:
                    //已完成
                    list[i].statusIcon = '../../../assets/icon/icon_complete.png';
                    list[i].statusTxt = '已完成';
                    if(list[i].IsComment == 0){
                        list[i].statusBtn = '去评价';
                    }
                    break;
                case 3:
                    //已退款
                    list[i].statusIcon = '../../../assets/icon/icon_complete.png';
                    list[i].statusTxt = '已解雇';
                    if (list[i].IsComment == 0) {
                        list[i].statusBtn = '去评价';
                    }
                    break;
            }
        }
    },
    //点击头像跳转到简历详情页
    selectProfileItem(e){
        let index = e.currentTarget.dataset.index;
        let resumeId = this.data.employeeList[index].ResumeInfoId;
        wx.navigateTo({
            url: '/pages/new-pages/resume-detail/resume-detail?resumeId=' + resumeId
        });
    },
    //雇员列表的条件过滤
    getMyEmployeeFilter(isReach){
        let data = {
            currentUserInfoId:app.userInfo.Id,
            orderType:this.data.positionId,
            pageIndex:0,
            pageSize:this.data.pageSize
        }
        let that = this;
        if (isReach){
            //下拉刷新
            if(!this.data.hasMore){
                return;
            }
            let pageI = ++that.data.pageIndex;
            data.pageIndex = pageI;
            that.setData({
                pageIndex: pageI
            });
            this.getMyEmployee(data);
        }else{
            //非下拉刷新
            that.setData({
                pageIndex:0,
                employeeList:[]
            })
            data.orderType = this.data.positionId;
            this.getMyEmployee(data);
        }
    },
    //结算方式
    clickPayWay(event) {
        let index = event.target.id;
        this.setData({
            positionId: index,
            pageIndex:-1,
            hasMore:true,
            employeeList:[]
        });
        this.getMyEmployeeFilter(false);
    },
    clickListItem(e){
        let index = e.currentTarget.dataset.index;
        let orderId = this.data.employeeList[index].Id;
        let flag = this.data.positionId;
        wx.navigateTo({
            url: '/pages/new-pages/my-employee-detail/my-employee-detail?orderId=' + orderId + "&flag=" + flag
        })
    },
    //状态按钮
    clickStatusbtn(e){
        let index = e.currentTarget.dataset.index;
        let flag = e.currentTarget.dataset.flag;
        let employeeObj = this.data.employeeList[index];
        let orderStatus = employeeObj.OrderStatus;
        let that = this;
        if (employeeObj.statusBtn == '去评价'){
            wx.navigateTo({
                url: '/pages/new-pages/employee-evaluate/employee-evaluate?employeeObj=' + JSON.stringify(employeeObj)
            })
            return;
        }
        switch(orderStatus){
            case 0:
                //支付订单
                this.prepayPayOrder(employeeObj);
                break;
            case 1:
                //已付款，修改订单为确认完成
                let data = {};
                let msg = '';
                data.OrderId = employeeObj.Id;
                if (flag){
                    data.OrderStatus = 2;
                    msg = '确认完成吗？您将支付订单全部时长的酬劳。详情参看->平台使用规则'
                }else{
                    data.OrderStatus = 3;
                    msg = "确认解雇吗？您将支付已工作时长的酬劳，剩余退还。详情参看->平台使用规则"
                }
                data.CurrentUserInfoId = app.userInfo.Id;
                wx.showModal({
                    title: '提示',
                    content: msg,
                    showCancel: true,
                    cancelText: '取消',
                    cancelColor: '#333',
                    confirmText: '确定',
                    confirmColor: '#4EB262',
                    success: function (res) {
                        if (res.confirm) {
                            that.updateResumeOrder(data);
                        }
                    }
                });
                break;
        }
    },
    clickDeleteOrder(e){
        let index = e.currentTarget.dataset.index;
        let employeeObj = this.data.employeeList[index];
        let that = this;
        wx.showModal({
            title: '提示',
            content: "你确认要删除订单吗？",
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#333',
            confirmText: '确定',
            confirmColor: '#4EB262',
            success: function (res) {
                if (res.confirm) {
                    that.deleteResumeOrder(employeeObj.Id);
                }
            }
        });
    },
    //删除订单
    deleteResumeOrder(id){
        let data = {};
        data.OrderId = id;
        data.CurrentUserInfoId = app.userInfo.Id;
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.deleteResumeOrder,
            data: data,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                console.log("buyResume response");
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        that.getMyEmployeeFilter(false);
                    } else {
                        Toast(res.data.Message);
                    }
                } else {
                    Toast("发起支付失败，请检查网络连接");
                }
            },
            fail: function (res) {
                console.log("buyResume fail", res);
                Toast("请求失败，请检查网络连接");
            },
            complete: function (res) { wx.hideLoading(); },
        })
    },
    //简历订单状态更新
    updateResumeOrder(data){
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.updateResumeOrder,
            data: data,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                console.log("buyResume response");
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        that.getMyEmployeeFilter(false);
                    } else {
                        Toast(res.data.Message);
                    }
                } else {
                    Toast("发起支付失败，请检查网络连接");
                }
            },
            fail: function (res) {
                console.log("buyResume fail", res);
                Toast("请求失败，请检查网络连接");
            },
            complete: function (res) { wx.hideLoading(); },
        })
    },
    prepayPayOrder(employeeObj){
        let data = {
            "WorkTime": 0,
            "OrderType": 0,
            "OrderAmount": 0,
            "SelectVIP": 0
        };
        data.UserInfoId = app.userInfo.Id;
        data.ResumeInfoId = employeeObj.ResumeInfoId;
        data.ContactNumber = employeeObj.ContactNumber;
        data.OrderType = this.data.positionId;
        data.Time = employeeObj.WorkTime;
        if (this.data.positionId == 1) {
            data.Time = employeeObj.Time;
            data.WorkTime = employeeObj.WorkTime;
        } else {
            data.Time = employeeObj.Time;
        }
        data.OrderAmount = employeeObj.OrderAmount;
        if (employeeObj.TotalFee - employeeObj.OrderAmount == 0){
            data.isOpenVip = 2;
        } else if (employeeObj.TotalFee - employeeObj.OrderAmount == 499){
            data.isOpenVip = 1;
        }else{
            data.isOpenVip = 0;
        }
        console.log("发起支付的参数" , data);
        this.startPay(data);
    },
    startPay(data){
        let that = this;
        wx.showLoading({
            title: '发起支付中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.buyResume,
            data: data,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                console.log("buyResume response");
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        wx.requestPayment({
                            timeStamp: res.data.BodyContent.timeStamp,
                            nonceStr: res.data.BodyContent.nonceStr,
                            package: res.data.BodyContent.package,
                            signType: res.data.BodyContent.signType,
                            paySign: res.data.BodyContent.paySign,
                            success: function (res) {
                                that.getMyEmployeeFilter(false);
                            },
                            fail: function (res) {
                                console.log("fail" + JSON.stringify(res));
                            },
                            complete: function (res) { },
                        })
                    } else {
                        Toast(res.data.Message);
                    }
                } else {
                    Toast("发起支付失败，请检查网络连接");
                }
            },
            fail: function (res) {
                console.log("buyResume fail", res);
                Toast("发起支付失败，请检查网络连接");
            },
            complete: function (res) { wx.hideLoading(); },
        })
    },
    toAgreement() {
        app.globalData.globalWebUrl = app.globalData.agreementUrl.employUrl;
        wx.navigateTo({
            url: '/pages/agreement-web/agreement-web?title=雇佣规则'
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getMyEmployeeFilter(false);
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        this.getMyEmployeeFilter(true);
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})